<template>
  <div class="container mx-auto p-4">
    <h1 class="text-2xl font-bold mb-4">代码片段管理器</h1>
    
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
      <!-- 左侧片段列表 -->
      <div class="space-y-4">
        <div class="flex justify-between items-center">
          <h2 class="text-lg font-semibold">片段列表</h2>
          <button
            @click="createNewSnippet"
            class="px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
          >
            新建
          </button>
        </div>
        
        <!-- 搜索框 -->
        <div class="relative">
          <input
            v-model="searchQuery"
            type="text"
            class="w-full pl-8 pr-3 py-2 border rounded-lg"
            placeholder="搜索片段..."
          />
          <span class="absolute left-2.5 top-2.5 text-gray-400">🔍</span>
        </div>

        <!-- 片段列表 -->
        <div class="space-y-2">
          <div
            v-for="snippet in filteredSnippets"
            :key="snippet.id"
            @click="selectSnippet(snippet)"
            class="p-3 border rounded-lg cursor-pointer hover:bg-gray-50 transition-colors"
            :class="{ 'border-blue-500 bg-blue-50': selectedSnippet?.id === snippet.id }"
          >
            <div class="font-medium">{{ snippet.title }}</div>
            <div class="text-sm text-gray-500">{{ snippet.language }}</div>
            <div class="text-xs text-gray-400 mt-1">{{ formatDate(snippet.updatedAt) }}</div>
          </div>
        </div>
      </div>

      <!-- 右侧编辑区 -->
      <div class="md:col-span-2 space-y-4">
        <div v-if="selectedSnippet" class="space-y-4">
          <div class="flex justify-between items-start">
            <div class="space-y-2 flex-1 mr-4">
              <input
                v-model="selectedSnippet.title"
                class="w-full px-3 py-2 border rounded-lg"
                placeholder="片段标题"
              />
              <div class="flex gap-2">
                <select
                  v-model="selectedSnippet.language"
                  class="px-3 py-2 border rounded-lg"
                >
                  <option value="javascript">JavaScript</option>
                  <option value="typescript">TypeScript</option>
                  <option value="html">HTML</option>
                  <option value="css">CSS</option>
                  <option value="python">Python</option>
                  <option value="java">Java</option>
                  <option value="sql">SQL</option>
                  <option value="shell">Shell</option>
                </select>
                <input
                  v-model="selectedSnippet.tags"
                  class="flex-1 px-3 py-2 border rounded-lg"
                  placeholder="标签（用逗号分隔）"
                />
              </div>
            </div>
            <div class="space-x-2">
              <button
                @click="saveSnippet"
                class="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 transition-colors"
              >
                保存
              </button>
              <button
                @click="deleteSnippet"
                class="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600 transition-colors"
              >
                删除
              </button>
            </div>
          </div>

          <textarea
            v-model="selectedSnippet.code"
            class="w-full h-[400px] p-4 font-mono border rounded-lg"
            placeholder="在此输入代码..."
          ></textarea>

          <div class="text-sm text-gray-500">
            最后更新: {{ formatDate(selectedSnippet.updatedAt) }}
          </div>
        </div>

        <div v-else class="h-[500px] flex items-center justify-center text-gray-400">
          选择或创建一个代码片段
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

interface CodeSnippet {
  id: string
  title: string
  code: string
  language: string
  tags: string
  createdAt: Date
  updatedAt: Date
}

// 使用 localStorage 持久化存储代码片段
const STORAGE_KEY = 'code-snippets'
const loadSnippets = (): CodeSnippet[] => {
  const stored = localStorage.getItem(STORAGE_KEY)
  if (!stored) return []
  try {
    const snippets = JSON.parse(stored)
    return snippets.map((s: any) => ({
      ...s,
      createdAt: new Date(s.createdAt),
      updatedAt: new Date(s.updatedAt)
    }))
  } catch (e) {
    return []
  }
}

const saveSnippetsToStorage = (snippets: CodeSnippet[]) => {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(snippets))
}

const snippets = ref<CodeSnippet[]>(loadSnippets())
const selectedSnippet = ref<CodeSnippet | null>(null)
const searchQuery = ref('')

// 过滤片段列表
const filteredSnippets = computed(() => {
  const query = searchQuery.value.toLowerCase()
  return snippets.value
    .filter((s: CodeSnippet) => 
      s.title.toLowerCase().includes(query) ||
      s.tags.toLowerCase().includes(query) ||
      s.language.toLowerCase().includes(query)
    )
    .sort((a: CodeSnippet, b: CodeSnippet) => b.updatedAt.getTime() - a.updatedAt.getTime())
})

// 创建新片段
const createNewSnippet = () => {
  const newSnippet: CodeSnippet = {
    id: Date.now().toString(),
    title: '新建片段',
    code: '',
    language: 'javascript',
    tags: '',
    createdAt: new Date(),
    updatedAt: new Date()
  }
  snippets.value.push(newSnippet)
  selectedSnippet.value = newSnippet
}

// 选择片段
const selectSnippet = (snippet: CodeSnippet) => {
  selectedSnippet.value = { ...snippet }
}

// 保存片段
const saveSnippet = () => {
  if (!selectedSnippet.value) return

  const index = snippets.value.findIndex((s: CodeSnippet) => s.id === selectedSnippet.value?.id)
  if (index === -1) return

  selectedSnippet.value.updatedAt = new Date()
  snippets.value[index] = { ...selectedSnippet.value }
  saveSnippetsToStorage(snippets.value)
}

// 删除片段
const deleteSnippet = () => {
  if (!selectedSnippet.value) return

  const index = snippets.value.findIndex((s: CodeSnippet) => s.id === selectedSnippet.value?.id)
  if (index === -1) return

  snippets.value.splice(index, 1)
  selectedSnippet.value = null
  saveSnippetsToStorage(snippets.value)
}

// 格式化日期
const formatDate = (date: Date) => {
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).format(date)
}
</script> 